var express = require('express');
var config = require('./config');
var redis = require('./modules/system/redis');
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
var path = require('path');
var fs = require('fs');
var favicon = require('serve-favicon');
var logger = require('morgan');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var RedisStore = require('connect-redis')(session);

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
    resave: true, // don't save session if unmodified
    saveUninitialized: false, // don't create session until something stored
    secret: 'love',
    store: new RedisStore({
        client : redis.client
    }),
    key:'express.sid'
}));

//设置静态文件的访问地址
app.use('/statics', express.static(__dirname + '/statics'))

//数据格式化
app.locals.dateFormat = function (date) {
    return moment(date).format('YYYY-MM-DD HH:mm:ss');
};

app.use(function(req, res, next) {
  if (!session || !session.user) {
    if(req.url.indexOf('/fv/') != -1) {
        res.redirect('/login');
    } else if(req.url.indexOf('/fj/') != -1) {
        res.json(global.result.notLogin);
    } else {
        next();//如果请求的地址是登录则通过，进行下一个请求
    }
  } else {
      next();
  }
});


// app.use('/', routes);
var routesPath = path.join(__dirname, 'routes/');
var filePaths = fs.readdirSync(routesPath);
for (var i in filePaths) {
    var fp = filePaths[i];
    if(fp.indexOf('.js') != -1) {
        app.use('/', require('./routes/' + fp.replace('.js', '')));
    } else {
        var files = fs.readdirSync(routesPath + fp);
        for (var i in files) {
            var name = files[i].replace('.js', '');
            app.use('/', require('./routes/' + fp + '/' + name));
        }
    }
}

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

process.on('uncaughtException', function (err) {
  console.log('Caught exception: ' + err);
});

if (cluster.isMaster) {
    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }
    cluster.on("exit", function(worker, code, signal) {
        cluster.fork();
    });
} else {
    //console.log('numCPUs:'+cluster);
    var server = app.listen(config.app.port, function () {
        var host = server.address().address;
        var port = server.address().port;
        console.log('应用实例，访问地址为 http://%s:%s', host, port);
    });
}


/*
var server = app.listen(config.app.port, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log('应用实例，访问地址为 http://%s:%s', host, port);

});*/